<?php

namespace app\middleware;

use app\Request;
use GuzzleHttp\Psr7\MimeType;
use think\helper\Str;
use think\Response;
use think\swoole\response\File;

class SwooleMiddleware
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, \Closure $next)
    {
        $url = str_replace($request->baseFile(), '', $request->baseUrl());
        if (strpos($url, '.') !== false && Str::startsWith($url, [
                '/admin/',
                '/static/',
                '/favicon',
                '/image/',
                '/uploads/',
                '/assets/'
            ])) {
            $filename = public_path() . ltrim($url, DIRECTORY_SEPARATOR);
            if (DIRECTORY_SEPARATOR == '\\') {
                $filename = str_replace('/', DIRECTORY_SEPARATOR, $filename);
            }
            if (file_exists($filename)) {
                $response = new File($filename);
                $contentType = MimeType::fromFilename($filename);
                if ($contentType) {
                    $response->header([
                        'Content-Type' => $contentType . '; charset=utf-8',
                    ]);
                }
                return $response;
            }
        }
        // 检查请求方法是否为 OPTIONS
        if ($request->method() == "OPTIONS") {
            // 返回允许跨域的响应
            return response('', 200, [
                'Access-Control-Allow-Origin'      => "*",
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Headers'     => '*',
                'Access-Control-Allow-Methods'     => '*',
            ]);
        }

        $response = $next($request);
        $response->header([
            'Access-Control-Allow-Origin'      => "*",
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers'     => '*',
            'Access-Control-Allow-Methods'     => '*',
        ]);
        return $response;
    }
}
